package com.ywj.chatroom.multiroom.server.handler;


import com.ywj.chatroom.multiroom.message.GroupJoinRequestMessage;
import com.ywj.chatroom.multiroom.message.GroupJoinResponseMessage;
import com.ywj.chatroom.multiroom.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
//import java.nio.channels.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * 加入群聊消息处理器
 * 1.获取自己的channel   2.把自己添加到group的map中
 * 3.拿到这个群里面的人的channel  4.给除了自己以外的所有人发通知有人加群了
 */
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        Channel channel = (Channel) ctx.channel();
        //加入group
        GroupSessionFactory.getGroupSession().joinMember(msg.getGroupName(), msg.getUsername());

//        List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(msg.getGroupName());
        List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(msg.getGroupName());

        //发送消息
        for (Channel users : membersChannel) {
            if(!users.equals(channel)){
                users.writeAndFlush(new GroupJoinResponseMessage(true, msg.getUsername() + "加入了聊天室"));
            }
        }
    }
}


